<?php

namespace Lib;

class Email {
	private $_oEmail = null;

	public function __construct() {
		global $o;
		try {
			$sPath = $o->Config->get ( '3thlib.path' );
			if ($sPath == null) {
				throw new ExceptionExt ( '第三方类库目录不存在' );
			}
			if (is_file ( $sPath . '/PHPMailer/class.phpmailer.php' )) {
				require_once $sPath . '/PHPMailer/class.phpmailer.php';
				$this->_oEmail = new \PHPMailer ();
				$this->setCharset ();
				$aSmtp = $o->Config->get ( 'smtp' );
				if ($aSmtp && $aSmtp ['host']) {
					$this->setStmp ( $aSmtp ['host'], $aSmtp ['port'], $aSmtp ['ssl'] );
					if ($aSmtp ['auth'] || $aSmtp ['username']) {
						$this->auth ( $aSmtp ['username'], $aSmtp ['password'] );
					}
				} else {
					$this->setMail ();
				}
			} else {
				throw new ExceptionExt ( '请先安装PHPMailer' );
			}
		} catch ( ExceptionExt $e ) {
			$e->showError ();
		}
	}

	/**
	 * 设置smtp服务器
	 *
	 * @param smtp服务器地址 $sHost        	
	 * @param 端口默认25 $iPort        	
	 * @param 是否使用ssl默认false $bSSL        	
	 */
	public function setStmp($sHost, $iPort = 25, $bSSL = false) {
		$this->_oEmail->IsSMTP ();
		$this->_oEmail->Host = $sHost;
		if ($iPort) {
			$this->_oEmail->Port = $iPort;
		}
		if ($bSSL) {
			$this->_oEmail->SMTPSecure = 'ssl';
		}
	}

	/**
	 * 设置使用php自带mail函数返送邮件
	 */
	public function setMail() {
		$this->_oEmail->IsMail ();
	}

	/**
	 * 设置smtp验证
	 *
	 * @param 用户名 $sUsername        	
	 * @param 密码 $sPassword        	
	 */
	public function auth($sUsername, $sPassword) {
		$this->_oEmail->SMTPAuth = true;
		$this->_oEmail->Username = $sUsername;
		$this->_oEmail->Password = $sPassword;
	}

	/**
	 * 设置字符集默认utf-8
	 *
	 * @param 字符集 $sCharset        	
	 */
	public function setCharset($sCharset = 'utf-8') {
		$this->_oEmail->CharSet = $sCharset;
	}

	/**
	 * 发邮件
	 *
	 * @param 发件人 $sFrom        	
	 * @param 收件人 $sTo        	
	 * @param 主题 $sSubject        	
	 * @param 内容 $sMessage        	
	 */
	public function send($sFrom, $sTo, $sSubject, $sMessage) {
		$this->_oEmail->Subject = $sSubject;
		$this->_oEmail->MsgHTML ( $sMessage );
		$this->_oEmail->SetFrom ( $sFrom );
		$this->_oEmail->AddAddress ( $sTo );
		$this->_oEmail->IsHtml ( true );
		$this->_oEmail->Send ();
		$this->_oEmail->ClearAllRecipients ();
	}

	public function clear() {
		$this->_oEmail->ClearAllRecipients ();
		$this->_oEmail->ClearAttachments ();
		$this->_oEmail->ClearCustomHeaders ();
	}

	public function __call($sName, $aParam) {
		if (method_exists ( $this->_oEmail, $sName )) {
			return call_user_func_array ( array (
					$this->_oEmail,
					$sName 
			), $aParam );
		} else {
			return false;
		}
	}
}

?>